/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package MeteoCal.controller;

import MeteoCal.bean.exceptions.IllegalOrphanException;
import MeteoCal.bean.exceptions.NonexistentEntityException;
import MeteoCal.bean.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import MeteoCal.entity.Event;
import MeteoCal.entity.Schedule;
import java.util.ArrayList;
import java.util.Collection;
import MeteoCal.entity.User;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author Daniele
 */
public class ScheduleJpaController implements Serializable {

    public ScheduleJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Schedule schedule) throws RollbackFailureException, Exception {
        if (schedule.getEventCollection() == null) {
            schedule.setEventCollection(new ArrayList<Event>());
        }
        if (schedule.getUserCollection() == null) {
            schedule.setUserCollection(new ArrayList<User>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Collection<Event> attachedEventCollection = new ArrayList<Event>();
            for (Event eventCollectionEventToAttach : schedule.getEventCollection()) {
                eventCollectionEventToAttach = em.getReference(eventCollectionEventToAttach.getClass(), eventCollectionEventToAttach.getIdEvent());
                attachedEventCollection.add(eventCollectionEventToAttach);
            }
            schedule.setEventCollection(attachedEventCollection);
            Collection<User> attachedUserCollection = new ArrayList<User>();
            for (User userCollectionUserToAttach : schedule.getUserCollection()) {
                userCollectionUserToAttach = em.getReference(userCollectionUserToAttach.getClass(), userCollectionUserToAttach.getEmail());
                attachedUserCollection.add(userCollectionUserToAttach);
            }
            schedule.setUserCollection(attachedUserCollection);
            em.persist(schedule);
            for (Event eventCollectionEvent : schedule.getEventCollection()) {
                eventCollectionEvent.getScheduleCollection().add(schedule);
                eventCollectionEvent = em.merge(eventCollectionEvent);
            }
            for (User userCollectionUser : schedule.getUserCollection()) {
                Schedule oldIdScheduleOfUserCollectionUser = userCollectionUser.getIdSchedule();
                userCollectionUser.setIdSchedule(schedule);
                userCollectionUser = em.merge(userCollectionUser);
                if (oldIdScheduleOfUserCollectionUser != null) {
                    oldIdScheduleOfUserCollectionUser.getUserCollection().remove(userCollectionUser);
                    oldIdScheduleOfUserCollectionUser = em.merge(oldIdScheduleOfUserCollectionUser);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Schedule schedule) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Schedule persistentSchedule = em.find(Schedule.class, schedule.getIdSchedule());
            Collection<Event> eventCollectionOld = persistentSchedule.getEventCollection();
            Collection<Event> eventCollectionNew = schedule.getEventCollection();
            Collection<User> userCollectionOld = persistentSchedule.getUserCollection();
            Collection<User> userCollectionNew = schedule.getUserCollection();
            List<String> illegalOrphanMessages = null;
            for (User userCollectionOldUser : userCollectionOld) {
                if (!userCollectionNew.contains(userCollectionOldUser)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain User " + userCollectionOldUser + " since its idSchedule field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Event> attachedEventCollectionNew = new ArrayList<Event>();
            for (Event eventCollectionNewEventToAttach : eventCollectionNew) {
                eventCollectionNewEventToAttach = em.getReference(eventCollectionNewEventToAttach.getClass(), eventCollectionNewEventToAttach.getIdEvent());
                attachedEventCollectionNew.add(eventCollectionNewEventToAttach);
            }
            eventCollectionNew = attachedEventCollectionNew;
            schedule.setEventCollection(eventCollectionNew);
            Collection<User> attachedUserCollectionNew = new ArrayList<User>();
            for (User userCollectionNewUserToAttach : userCollectionNew) {
                userCollectionNewUserToAttach = em.getReference(userCollectionNewUserToAttach.getClass(), userCollectionNewUserToAttach.getEmail());
                attachedUserCollectionNew.add(userCollectionNewUserToAttach);
            }
            userCollectionNew = attachedUserCollectionNew;
            schedule.setUserCollection(userCollectionNew);
            schedule = em.merge(schedule);
            for (Event eventCollectionOldEvent : eventCollectionOld) {
                if (!eventCollectionNew.contains(eventCollectionOldEvent)) {
                    eventCollectionOldEvent.getScheduleCollection().remove(schedule);
                    eventCollectionOldEvent = em.merge(eventCollectionOldEvent);
                }
            }
            for (Event eventCollectionNewEvent : eventCollectionNew) {
                if (!eventCollectionOld.contains(eventCollectionNewEvent)) {
                    eventCollectionNewEvent.getScheduleCollection().add(schedule);
                    eventCollectionNewEvent = em.merge(eventCollectionNewEvent);
                }
            }
            for (User userCollectionNewUser : userCollectionNew) {
                if (!userCollectionOld.contains(userCollectionNewUser)) {
                    Schedule oldIdScheduleOfUserCollectionNewUser = userCollectionNewUser.getIdSchedule();
                    userCollectionNewUser.setIdSchedule(schedule);
                    userCollectionNewUser = em.merge(userCollectionNewUser);
                    if (oldIdScheduleOfUserCollectionNewUser != null && !oldIdScheduleOfUserCollectionNewUser.equals(schedule)) {
                        oldIdScheduleOfUserCollectionNewUser.getUserCollection().remove(userCollectionNewUser);
                        oldIdScheduleOfUserCollectionNewUser = em.merge(oldIdScheduleOfUserCollectionNewUser);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = schedule.getIdSchedule();
                if (findSchedule(id) == null) {
                    throw new NonexistentEntityException("The schedule with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Schedule schedule;
            try {
                schedule = em.getReference(Schedule.class, id);
                schedule.getIdSchedule();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The schedule with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<User> userCollectionOrphanCheck = schedule.getUserCollection();
            for (User userCollectionOrphanCheckUser : userCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Schedule (" + schedule + ") cannot be destroyed since the User " + userCollectionOrphanCheckUser + " in its userCollection field has a non-nullable idSchedule field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Event> eventCollection = schedule.getEventCollection();
            for (Event eventCollectionEvent : eventCollection) {
                eventCollectionEvent.getScheduleCollection().remove(schedule);
                eventCollectionEvent = em.merge(eventCollectionEvent);
            }
            em.remove(schedule);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Schedule> findScheduleEntities() {
        return findScheduleEntities(true, -1, -1);
    }

    public List<Schedule> findScheduleEntities(int maxResults, int firstResult) {
        return findScheduleEntities(false, maxResults, firstResult);
    }

    private List<Schedule> findScheduleEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Schedule.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Schedule findSchedule(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Schedule.class, id);
        } finally {
            em.close();
        }
    }

    public int getScheduleCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Schedule> rt = cq.from(Schedule.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
